package com.project.dao.Impl;

import com.project.bean.SpeakBean;
import com.project.bean.UserBean;
import com.project.dao.ISpeakDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Repository
public class SpeakDaoImpl extends BaseDao implements ISpeakDao {

    @Override
    public List<SpeakBean> findByProduct(int productId) {
        List<SpeakBean> list=new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT s.* ,u.u_nickName FROM t_user u ,t_speak s WHERE u.pk_userId = s.fk_userId AND s.fk_productId=?");
            ps.setObject(1,productId);
            rs=ps.executeQuery();
            while (rs.next()){
                SpeakBean speakBean = new SpeakBean();
                speakBean.setId(rs.getInt("pk_speakId"));
                speakBean.setContent(rs.getString("s_content"));
                UserBean userBean = new UserBean();
                userBean.setNickname((rs.getString("u_nickName")));
                speakBean.setUserBean(userBean);
                list.add(speakBean);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }

        return list;
    }

    @Override
    public void addSpeak(SpeakBean speak) {
        this.setConnection();
        try {
            ps=con.prepareStatement("INSERT INTO t_speak(fk_userId,s_content,fk_productId)\n" +
                    "VALUES (?,?,?)");
            ps.setObject(1,speak.getUserBean().getId());
            ps.setObject(2,speak.getContent());
            ps.setObject(3,speak.getProductBean().getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
    }
}
